<template>
  <view class="video-player-page">
    <!-- 顶部导航栏 -->
    <up-navbar :title="lessonTitle" :bgColor="bgColor" height="50" fixed placeholder>
      <template #left>
        <up-icon name="arrow-left" @click="goBack"></up-icon>
      </template>
    </up-navbar>

    <!-- 视频播放器 -->
    <view class="video-container">
      <view class="video-player-wrapper">
        <video 
          v-if="videoSrc" 
          :src="videoSrc" 
          :controls="true"
          :autoplay="false" 
          :show-fullscreen-btn="true" 
          :show-play-btn="true" 
          :show-center-play-btn="true"
          :enable-progress-gesture="true" 
          :vslide-gesture="true" 
          :vslide-gesture-in-fullscreen="true"
          :enable-play-gesture="true" 
          object-fit="contain"
          :poster="videoPoster" 
          :direction="0" 
          :initial-time="0"
          class="video-player" 
          @play="onVideoPlay" 
          @pause="onVideoPause" 
          @ended="onVideoEnded"
          @error="onVideoError" 
          @fullscreenchange="onFullscreenChange" 
          @loadstart="onVideoLoad"
          @loadeddata="onVideoLoaded" 
          id="courseVideoPlayer">
        </video>
        
        <!-- 视频加载状态 -->
        <view v-else-if="isVideoLoading" class="video-loading">
          <view class="loading-spinner"></view>
          <text class="loading-text">视频加载中...</text>
        </view>
        
        <!-- 视频占位符 -->
        <view v-else class="video-placeholder">
          <up-icon name="play-circle" color="#ccc" size="60"></up-icon>
          <text class="placeholder-text">视频资源加载失败</text>
        </view>
      </view>
    </view>

    <!-- 课程信息 -->
    <view class="course-info-section">
      <view class="course-title">{{ courseTitle }}</view>
      <view class="lesson-title">{{ lessonTitle }}</view>
      
      <!-- 进度条 -->
      <view class="progress-section">
        <view class="progress-label">学习进度</view>
        <up-slider 
          v-model="playProgress" 
          :min="0" 
          :max="100" 
          :step="1" 
          :showValue="false"
          :disabled="false"
          barColor="#4ecdc4"
          inactiveColor="#e0e0e0"
          @change="onProgressChange">
        </up-slider>
        <view class="progress-text">
          <text>{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</text>
        </view>
      </view>
    </view>

    <!-- 相关课程 -->
    <view class="related-section">
      <view class="section-title">相关课程</view>
      <scroll-view scroll-x class="related-scroll">
        <view class="related-list">
          <view 
            class="related-item" 
            v-for="(item, index) in relatedCourses" 
            :key="index"
            @click="goToCourse(item.id)"
          >
            <image :src="item.cover" class="related-cover" mode="aspectFill"></image>
            <view class="related-info">
              <text class="related-title">{{ item.title }}</text>
              <text class="related-instructor">{{ item.instructor }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 课程目录 -->
    <view class="catalog-section">
      <view class="section-title">课程目录</view>
      <view class="catalog-list">
        <view 
          class="catalog-item" 
          v-for="(lesson, index) in lessonList" 
          :key="index"
          :class="{ active: currentLessonIndex === index }"
          @click="switchLesson(index)"
        >
          <view class="lesson-info">
            <up-icon 
              :name="lesson.isPlayed ? 'checkmark-circle-fill' : 'play-circle'" 
              size="16" 
              :color="lesson.isPlayed ? '#4ecdc4' : '#999'"
            ></up-icon>
            <text class="lesson-title">{{ lesson.title }}</text>
          </view>
          <view class="lesson-meta">
            <text class="lesson-duration">{{ lesson.duration }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'

// 页面数据
const bgColor = ref('#fff')
const isVideoLoading = ref(false)
const playProgress = ref(0)
const currentTime = ref(0)
const duration = ref(0)
const currentLessonIndex = ref(0)

// 视频数据
const videoSrc = ref('')
const videoPoster = ref('')
const courseTitle = ref('')
const lessonTitle = ref('')

// 相关课程
const relatedCourses = reactive([
  {
    id: 2,
    title: '颜真卿楷书入门',
    instructor: '李老师',
    cover: 'https://cdn.vxexpo.com/58d5bc94b9dc12f9341ea979c4a862ce1b98a83a/19214/12102/textures/98bf328cce8d2ddc167dc09be1de8561.jpg'
  },
  {
    id: 3,
    title: '草书笔法解析',
    instructor: '王老师',
    cover: 'https://cdn.vxexpo.com/58d5bc94b9dc12f9341ea979c4a862ce1b98a83a/19214/12102/textures/98bf328cce8d2ddc167dc09be1de8561.jpg'
  },
  {
    id: 4,
    title: '隶书结构分析',
    instructor: '赵老师',
    cover: 'https://cdn.vxexpo.com/58d5bc94b9dc12f9341ea979c4a862ce1b98a83a/19214/12102/textures/98bf328cce8d2ddc167dc09be1de8561.jpg'
  }
])

// 课程目录
const lessonList = reactive([
  { title: '王羲之生平介绍', duration: '15:30', isPlayed: true },
  { title: '行书发展历史', duration: '18:20', isPlayed: true },
  { title: '王羲之书法风格特点', duration: '22:15', isPlayed: false },
  { title: '点画的写法', duration: '12:45', isPlayed: false },
  { title: '横画的写法', duration: '14:20', isPlayed: false },
  { title: '竖画的写法', duration: '16:30', isPlayed: false },
  { title: '撇画的写法', duration: '13:45', isPlayed: false }
])

// 页面初始化
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const current = pages[pages.length - 1]
  const options = current.options || {}
  
  const courseId = options.courseId || 1
  lessonTitle.value = decodeURIComponent(options.lessonTitle || '课程视频')
  
  // 设置课程标题
  courseTitle.value = '王羲之行书技法精讲'
  
  // 设置视频源（模拟）
  videoSrc.value = 'https://shishuhuayin.com.cn/luoshenfu.mp4'
  videoPoster.value = 'https://cdn.vxexpo.com/58d5bc94b9dc12f9341ea979c4a862ce1b98a83a/19214/12102/textures/98bf328cce8d2ddc167dc09be1de8561.jpg'
  
  // 初始化视频上下文
  initVideoContext()
})

// 页面销毁时清理
onUnmounted(() => {
  // 清理定时器等
})

// 初始化视频上下文
const initVideoContext = () => {
  // 在实际项目中，这里会初始化视频上下文
  // const videoContext = uni.createVideoContext('courseVideoPlayer', this)
}

// 页面跳转
const goBack = () => {
  uni.navigateBack()
}

const goToCourse = (id) => {
  uni.navigateTo({
    url: `/gallery_pages/course/detail?id=${id}`
  })
}

// 切换课程
const switchLesson = (index) => {
  currentLessonIndex.value = index
  const lesson = lessonList[index]
  lessonTitle.value = lesson.title
  
  // 模拟切换视频源
  uni.showToast({
    title: `切换到：${lesson.title}`,
    icon: 'none'
  })
}

// 视频事件处理
const onVideoPlay = () => {
  console.log("视频开始播放")
  isVideoLoading.value = false
}

const onVideoPause = () => {
  console.log("视频暂停")
}

const onVideoEnded = () => {
  console.log("视频播放结束")
  // 标记当前课程为已学习
  if (lessonList[currentLessonIndex.value]) {
    lessonList[currentLessonIndex.value].isPlayed = true
  }
  
  uni.showToast({
    title: "视频播放结束",
    icon: "none"
  })
}

const onVideoError = (e) => {
  console.error("视频播放错误:", e)
  isVideoLoading.value = false
  uni.showToast({
    title: "视频播放出错，请检查网络",
    icon: "none"
  })
}

const onFullscreenChange = (e) => {
  console.log("视频全屏状态改变:", e)
  if (e.detail.fullScreen) {
    console.log("进入全屏")
  } else {
    console.log("退出全屏")
  }
}

const onVideoLoad = () => {
  console.log("视频加载中")
  isVideoLoading.value = true
}

const onVideoLoaded = () => {
  console.log("视频加载完成")
  isVideoLoading.value = false
}

// 进度条事件
const onProgressChange = (value) => {
  console.log("进度条变化:", value)
  // 在实际项目中，这里会跳转到指定时间点
}

// 时间格式化
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>

<style lang="scss" scoped>
.video-player-page {
  min-height: 100vh;
  background: #f5f6fa;
}

.video-container {
  background: #000;
  
  .video-player-wrapper {
    width: 100%;
    height: 420rpx;
    position: relative;
    
    .video-player {
      width: 100%;
      height: 100%;
    }
    
    .video-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      background: #000;
      
      .loading-spinner {
        width: 40rpx;
        height: 40rpx;
        border: 4rpx solid #ccc;
        border-top-color: #333;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
      
      .loading-text {
        font-size: 28rpx;
        color: #fff;
        margin-top: 20rpx;
      }
    }
    
    .video-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      background: #000;
      
      .placeholder-text {
        font-size: 28rpx;
        color: #fff;
        margin-top: 20rpx;
      }
    }
  }
}

.course-info-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .course-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .lesson-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 30rpx;
  }
  
  .progress-section {
    .progress-label {
      font-size: 26rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .progress-text {
      display: flex;
      justify-content: space-between;
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
}

.related-section, .catalog-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.related-scroll {
  width: 100%;
  white-space: nowrap;
  
  .related-list {
    display: inline-flex;
    
    .related-item {
      width: 280rpx;
      margin-right: 20rpx;
      border-radius: 15rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      background: #fff;
      
      .related-cover {
        width: 100%;
        height: 160rpx;
      }
      
      .related-info {
        padding: 15rpx;
        
        .related-title {
          display: block;
          font-size: 26rpx;
          color: #333;
          margin-bottom: 10rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .related-instructor {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }
}

.catalog-list {
  .catalog-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
    
    &.active {
      .lesson-info {
        .lesson-title {
          color: #4ecdc4;
          font-weight: 500;
        }
      }
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .lesson-info {
      display: flex;
      align-items: center;
      flex: 1;
      
      .lesson-title {
        font-size: 26rpx;
        color: #333;
        margin-left: 15rpx;
      }
    }
    
    .lesson-meta {
      .lesson-duration {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>